package com.huluobo.a2109kotlinshopping.cart

import android.content.Intent
import android.util.Log
import android.widget.CheckBox
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.huluobo.a2109kotlinshopping.R
import com.huluobo.a2109kotlinshopping.base.BaseMVVMFragment
import com.huluobo.a2109kotlinshopping.databinding.FragmentCartBinding
import com.huluobo.a2109kotlinshopping.db.DatabaseUtil
import com.huluobo.a2109kotlinshopping.order.PayActivity
import org.w3c.dom.Text

class CartFragment : BaseMVVMFragment<FragmentCartBinding>() {
    private lateinit var viewModel: CartViewModel

    private lateinit var adapter: CartAdapter

    //购物车数据源
    private val cartList = mutableListOf<CartBean>()
    override fun getLayoutId(): Int = R.layout.fragment_cart

    override fun initData() {
        viewModel = ViewModelProvider(requireActivity())[CartViewModel::class.java]

        //进入页面初始化时获取购物车数据
        viewModel.getCartList()

        //购车数据成功的反馈
        viewModel.getCartListSuccess.observe(this) {
            if (it.code == 200) {
                cartList.clear()
                cartList.addAll(it.data)
                adapter.notifyDataSetChanged()
            }
        }

        //删除购物车成功反馈
        viewModel.deleteCartSuccess.observe(this) {
            if (it.code == 200) {
                ToastUtils.showLong(it.message)
            }
        }

        viewModel.addSuccess.observe(this) {
            if (it.code == 200) {
                ToastUtils.showLong("购物车数量+1")
            }
        }

        viewModel.removeSuccess.observe(this) {
            if (it.code == 200) {
                ToastUtils.showLong("购物车数量-1")
            }
        }
    }

    override fun initView() {
        //初始化购物车列表
        dataBinding.cartRv.layoutManager = LinearLayoutManager(requireContext())
        adapter = CartAdapter(cartList)
        dataBinding.cartRv.adapter = adapter

        //全选按钮点击事件
        dataBinding.cartCbSelectAll.setOnCheckedChangeListener { buttonView, isChecked ->
            dataBinding.cartCbSelectAll.setOnClickListener {
                cartList.forEach {
                    it.isChecked = isChecked
                }
                adapter.notifyDataSetChanged()
                totalPrice()
            }
        }


        //支付按钮点击事件
        dataBinding.cartTvPay.setOnClickListener {
            //点击支付按钮时,把购物车中所有的已勾选的项保存到订单表中
            val orderList = mutableListOf<CartBean>()
            cartList.forEach {
                if (it.isChecked) {
                    orderList.add(it)
                }
            }
            //保存订单信息到数据库
            DatabaseUtil.getDb().orderDao().insertOrderBeanList(orderList)

            val intent = Intent(requireContext(), PayActivity::class.java)
            startActivity(intent)
        }

        //设置adapter中的item的id可点击
        adapter.addChildClickViewIds(
            R.id.cart_item_cb,
            R.id.cart_item_delete,
            R.id.cart_item_iv_add,
            R.id.cart_item_iv_reduce
        )

        //item的点击事件
        adapter.setOnItemChildClickListener { adapter, view, position ->
            when (view.id) {
                //选中按钮的点击事件
                R.id.cart_item_cb -> {
                    //选中按钮取反值
                    cartList[position].isChecked = !cartList[position].isChecked
                    //单独刷新一个view
                    (adapter.getViewByPosition(position, R.id.cart_item_cb) as CheckBox).isChecked =
                        cartList[position].isChecked
                }
                //删除按钮的点击事件
                R.id.cart_item_delete -> {
                    val ids = cartList[position].id.toString()
                    viewModel.deleteCart(ids)
                    cartList.removeAt(position)
                    adapter.notifyItemRemoved(position)
                }

                //加号的点击事件
                R.id.cart_item_iv_add -> {
                    cartList[position].count += 1
                    viewModel.addCart(1, cartList[position].goods_id)
                    //局部刷新一个item的数量
                    (adapter.getViewByPosition(position, R.id.cart_item_tv_num) as TextView).text =
                        "${cartList[position].count}"
                }

                //减号的点击事件
                R.id.cart_item_iv_reduce -> {
                    if (cartList[position].count > 1) {
                        viewModel.removeCart(-1, cartList[position].goods_id)
                        cartList[position].count -= 1
                        //局部刷新一个item的数量
                        (adapter.getViewByPosition(position, R.id.cart_item_tv_num) as TextView).text =
                            "${cartList[position].count}"
                    }
                }
            }
            //无论点击了item中哪一个按钮,都需要重新计算一次总价
            totalPrice()
            checkIsAll()
        }
        //初始化时也需要就按一次总价
        totalPrice()

    }

    private fun totalPrice() {
        var totalPrice = 0

        cartList.forEach {
            if (it.isChecked) {
                totalPrice += it.goods_default_price * it.count
            }
        }
        //检查list中是否存在false 通过in来检查一个值是否在一个集合中,这里加叹号表示不在当前集合中
        // false !in checkList 会返回boolean值,如果false不在集合中就返回true,在集合中就返回false
        //通过这个boolean值来给全选按钮的是否选中赋值

        dataBinding.cartTvTotalPrice.text = "总价:￥$totalPrice"
    }

    private fun checkIsAll() {
        val checkList = mutableListOf<Boolean>()
        cartList.forEach {
            //将购物车中所有的是否选中放到一个集合中
            checkList.add(it.isChecked)
        }
        dataBinding.cartCbSelectAll.isChecked = false !in checkList
    }
}